package v1

import (
	"errors"
	"fmt"
	"gin-example/pkg/e"
	"github.com/gin-gonic/gin"
	"github.com/nfnt/resize"
	"image"
	"image/jpeg"
	"image/png"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func Login(c *gin.Context) {
	code := e.INVALID_PARAMS

	_ = c.Query("username")
	_ = c.Query("password")

	if true {
		code = e.SUCCESS
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"token": "123456",
		"data": make(map[string]interface{}),
	})
}

func GetUserInfo(c *gin.Context) {
	code := e.SUCCESS
	data := make(map[string]interface{})
	data["name"] = "tmp"
	data["avatar"] = "avatar"

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"token": "123456",
		"data": data,
	})
}

func UploadPic(c *gin.Context) {
	f, err := c.FormFile("f1")
	//错误处理
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err,
		})
		return
	} else {
		originName := f.Filename
		splitIdx := strings.LastIndex(originName, ".")
		fileType := originName[splitIdx:]

		//将文件保存至本项目根目录中
		filename := strconv.FormatInt(time.Now().UnixNano(), 10)
		filePath := "assets/" + filename + fileType
		err = c.SaveUploadedFile(f, filePath)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"message": "保存上传图片异常"})
			fmt.Println(err)
			return
		}
		if tmpPath, err := TryCompressPic(filePath, fileType); err == nil {
			filePath = tmpPath
		} else {
			fmt.Println("压缩图片异常：", err)
		}

		//保存成功返回正确的Json数据
		c.JSON(http.StatusOK, gin.H{
			"code": e.SUCCESS,
			"message": "OK",
			"raw": filePath,
		})
	}
}

func TryCompressPic(filepath, fileType string) (compressPath string, err error) {
	file, err := os.Open(filepath)
	if err != nil {
		return
	}

	// decode jpeg into image.Image
	var img image.Image
	var c image.Config
	var interp resize.InterpolationFunction

	if strings.HasSuffix(fileType, "png") {
		img, err = png.Decode(file)
		c, _ = png.DecodeConfig(file)
		interp = resize.NearestNeighbor
	} else {
		img, err = jpeg.Decode(file)
		interp = resize.Lanczos3
		c, _ = jpeg.DecodeConfig(file)
	}

	if err != nil {
		return
	}
	if c.Width < 800 {
		return "", errors.New("不需要压缩")
	}
	compWidth := uint(MinInt(c.Width, 800))

	file.Close()

	m := resize.Resize(compWidth, 0, img, interp)

	compressPath = strings.TrimSuffix(filepath, fileType) + "-cmp" + fileType

	out, err := os.Create(compressPath)
	if err != nil {
		return
	}
	defer out.Close()

	// write new image to file
	if strings.HasSuffix(fileType, "png") {
		png.Encode(out, m)
	} else {
		jpeg.Encode(out, m, nil)
	}
	return
}

func MinInt(x, y int) int {
	if x > y {
		return y
	} else {
		return x
	}
}